import React, { useEffect, useMemo } from 'react'
import './index.less'
import { useSetState } from 'ahooks'
import { Button } from 'antd'
export default (props: any) => {
  const { maxRows = 3 } = props
  //因为可能一个页面有多个这样的容器，确保id唯一
  let randomId = parseInt(Math.random() * 100000)
  const containerId = `container-${randomId}`
  const innerBoxId = `inner-box-${randomId}`
  const [state, setState] = useSetState<any>({
    targetDom: null,
    //文段原本有多少行
    rows: 0,
    //展示的数据
    showText: '',
    //默认收缩
    expand: false
  })
  const showCollapseBtn = useMemo(() => {
    return state.rows > maxRows
  }, [state.rows])
  const text = useMemo(() => {
    if (showCollapseBtn) {
      return state.expand ? props.text : state.showText
    } else {
      return props.text
    }
  }, [showCollapseBtn, state.expand])
  useEffect(() => {
    let targetDom = (document as any).getElementById(innerBoxId)
    let targetRects = targetDom.getClientRects()
    //获取行数
    let rows = getLength(targetRects)
    let showText = getShowText(rows)
    setState({
      rows,
      showText,
      targetDom
    })
  }, [])
  const getShowText = (rows: number) => {
    let targetDom = (document as any).getElementById(innerBoxId)
    let step = 1
    let showText = targetDom.innerHTML
    while (rows > maxRows) {
      showText = showText.slice(0, -step)
      //加两个占位符 ，将收缩按钮定位到这2个占位符的位置
      targetDom.innerHTML = showText + `...&#8195;&#8195;`
      rows = getLength(targetDom.getClientRects())
    }
    return showText + `...`
  }
  const getLength = (rects: any) => {
    let line = 0
    let lastBottom = 0
    for (let i = 0, len = rects.length; i < len; i++) {
      if (rects[i].bottom == lastBottom) {
        continue
      }
      lastBottom = rects[i].bottom
      line++
    }
    return line
  }
  return (
    <div id={containerId} className="expand-shrink-text-container">
      <span id={innerBoxId}>{text}</span>
      {showCollapseBtn && (
        <Button
          type="link"
          className={state.expand ?'expand-shrink-btn':'shrink-status'}
          onClick={()=>{
            setState({
              expand:!state.expand
            })
          }}>
          {state.expand ? '收缩' : '展开'}
        </Button>
      )}
    </div>
  )
}
